package com.idap.testr;

import java.io.File;

import org.math.R.RserverConf;
import org.math.R.Rsession;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;


public class Rtest {  
	public static void main(String[] args) throws REXPMismatchException,REngineException {
	 //建立连接
//	  RConnection c = new RConnection();  
//	  //REXP x = c.eval("R.version.string");
	  RserverConf rconf = new RserverConf();
	  Rsession s = Rsession.newInstanceTry(System.out, rconf);
	  
//    执行R脚本	  
	  double[] rand = s.eval("rnorm(5)").asDoubles();
	  for(double ran:rand){
	      System.out.print(ran+",");
	  }

	  //创建一个data.frame对象
//	  s.set("df", new double[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } }, "x1", "x2", "x3");
//	  double df$x1_3 = s.eval("df$x1[3]").asDouble();
//	  System.out.println(df$x1_3);
//	  s.rm("df");
	  
	  //在本地生成一个图形文件
//	  s.toJPEG(new File("D:/output/plot.png"), 400, 400, "plot(rnorm(10))");  
	  
	  //以HTML格式输出
//	  String html = s.asHTML("summary(rnorm(100))");
//	  System.out.println(html);
	
	  //以文本格式暑输出
//	  String txt = s.asString("summary(rnorm(100))"); // format in text
//	  System.out.println(txt);
	  
	  //安装新类库
//	  System.out.println(s.installPackage("sensitivity", true));
	  
	  //聚类！
//	  s.eval("data(iris)");
//	  s.eval("attach(iris)");
//	  s.eval("plclust( hclust( dist(iris[,1:4])), labels = FALSE, hang = -1)");
	  
	  //花萼那个数据集图，系统据聚类法
//	  s.toJPEG(new File("D:/output/good1.png"), 1000, 600, "data(iris);attach(iris);plclust( hclust( dist(iris[,1:4])), labels = FALSE, hang = -1)");
	  
	  //一个线性图
	  //s.toJPEG(new File("D:/output/good.png"), 1000, 600, " x<-seq(-10,10,0.1);plot(x,y=x,type='l');lines(x,y=x*x,type='l')");
	  
	  //动态聚类法
//	  s.toJPEG(new File("D:/output/good.png"), 1000, 600, "library(fpc);"
//													  		+ "data(iris);"
//													  		+ "df<-iris[,c(1:4)];"
//													  		+ "set.seed(252964);"
//													  		+ "(kmeans <- kmeans(na.omit(df), 3));"
//													  		+ "plotcluster(na.omit(df), kmeans$cluster)");
	  //自己生成图
	  //s.toJPEG(new File("D:/output/Orange.png"), 1000, 600, "plot(Orange$circumference,Orange$age)");
	  
	  //plot方法生成图
	  s.toJPEG(new File("D:/output/test.png"), 1000, 600,  "newiris <- iris;"
														  		+ "newiris$Species <- NULL;"
														  		+ "kc <- kmeans(newiris,4);"
														  		+ "plot(newiris[c('Sepal.Length', 'Sepal.Width')], col = kc$cluster)");
	}  
}  